//
//  FillInTheOrderViewModel.m
//  GLGW_Shoping
//
//  Created by yang on 2018/11/27.
//  Copyright © 2018年 yang. All rights reserved.
//

#import "FillInTheOrderViewModel.h"
#import "FillBottomView.h"
#import "FillExpressTableViewCell.h"
#import "AdressSelectTableViewCell.h"
#import "OrderGoodsTableViewCell.h"
#import "FillGoodsMoneyTableViewCell.h"
#import "FillAdressSelectTableViewCell.h"
#import "WithDrawlRecordDetailTableViewCell.h"
#import "ToPayOrderModel.h"
#import "OrderGoodsAddressModel.h"

@interface FillInTheOrderViewModel ()<UITableViewDelegate,UITableViewDataSource>
{
    NSInteger iskkkkkk;
    NSInteger distribution;
    UITableView *selfTableView;
    FillBottomView *fillView;
}
@property (nonatomic, strong) ToPayOrderModel *model;
@end

@implementation FillInTheOrderViewModel

- (instancetype)initWithViewToViewModel:(UITableView *)tableView theSuperView:(UIView *)superView
{
    if (self = [super initWithViewToViewModel:tableView theSuperView:superView]) {
        iskkkkkk = 1;
        tableView.backgroundColor = [UIColor colorWithHexString:@"#F2F2F2"];
        tableView.height = tableView.height - kHeightProportion_In_iPhoneTriploid(60);
        tableView.mj_header.hidden = YES;
        tableView.mj_footer.hidden = YES;
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.estimatedRowHeight = 22;
        tableView.rowHeight = UITableViewAutomaticDimension;
//        tableView.tableFooterView = [self createFootView];
        [superView addSubview:tableView];
        selfTableView = tableView;
        distribution = 1;
        self.addressModel = [MyAdressModel_Infos new];
        self.addressModel.consignee = @"收货人";
        self.addressModel.phone = @"123123";
        self.addressModel.warehouseName = @"仓库仓库1号";
        self.addressModel.address = @"地址河北省js-sdfafsd";
        
        self.lastPageModel = [FillExpressModel new];
        self.lastPageModel.topStr = @"卖家承运";
        self.lastPageModel.detailStr = @"由卖方发货，并提供售后服务";
        
        fillView = [[FillBottomView alloc] initWithFrame:CGRectMake(0, kY_With_View(tableView, 0), KScreenWidth, kHeightProportion_In_iPhoneTriploid(60)) inSuperView:superView];
        [fillView.payMoneyBut addTarget:self action:@selector(payMoney:) forControlEvents:UIControlEventTouchUpInside];
        kWeakSelf(self);
        fillView.BlockCallBtn = ^{
            [weakself call];
        };
    }
    return self;
}

- (UIView *)createFootView {
    UIView * footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, kHeightProportion_In_iPhoneTriploid(10))];
    footView.backgroundColor = [UIColor colorWithHexString:@"#F2F2F2"];
    return footView;
}

#pragma mark --- UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger cellNum;
    switch (section) {
        case 0:{
            cellNum = 3;
        }
            break;
        case 1:{
            if (self.model) {
               cellNum = self.model.data.info.orderGoods.count;
            } else {
                cellNum = 4;
            }
        }
            break;
        default:
            cellNum = 1;
            break;
    }
    return cellNum;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat cellHeight;
    switch (indexPath.section) {
        case 0:{
            if (indexPath.row == 0) {
                cellHeight = kHeightProportion_In_iPhoneTriploid(60);
            } else if (indexPath.row == 1){
                return UITableViewAutomaticDimension;
            } else {
                cellHeight = kHeightProportion_In_iPhoneTriploid(44);
            }
        }
            break;
        case 1:{
            cellHeight = kHeightProportion_In_iPhoneTriploid(122);
        }
            break;
        case 3:{
            cellHeight = kHeightProportion_In_iPhoneTriploid(81);
        }
            break;
            
        default:
            cellHeight = kHeightProportion_In_iPhoneTriploid(44);
            break;
    }
    return cellHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BaseTableViewCell * cell;
    switch (indexPath.section) {
        case 0:{
            if (indexPath.row == 0) {
                FillExpressTableViewCell * cell_express = [FillExpressTableViewCell cellWithTableView:tableView];
                cell_express.expressModel = self.lastPageModel;
                cell_express.showPush = YES;
                cell = cell_express;
            } else if (indexPath.row == 1) {
                if (self.addressModel) {
                    FillAdressSelectTableViewCell * cell_ware = [FillAdressSelectTableViewCell cellWithTableView:tableView];
                    cell_ware.showPush = YES;
                    cell_ware.inforModel = self.addressModel;
                    cell = cell_ware;
                } else {
                    WithDrawlRecordDetailTableViewCell *detailCell = [WithDrawlRecordDetailTableViewCell cellWithTableView:tableView];
                    detailCell.leftColorStr = @"#333333";
                    detailCell.rightLab.hidden = YES;
                    detailCell.showPush = YES;
                    detailCell.leftStr = @"选择收货地址";
                    return detailCell;
                }
            } else {
                AdressSelectTableViewCell * cell_adress = [AdressSelectTableViewCell cellWithTableView:tableView];
                cell_adress.showPush = YES;
                cell_adress.leftTitString = @"付款方式";
                cell = cell_adress;
            }
        }
            break;
        case 1:{
            OrderGoodsTableViewCell * cell_goods = [OrderGoodsTableViewCell cellWithTableView:tableView];
            if (self.model) {
                ToPayOrderDataModel *listModel = self.model.data.info;
                [cell_goods refreshToPayOrderCell:listModel index:indexPath];
            }
            cell = cell_goods;
        }
            break;
        case 2:{
            AdressSelectTableViewCell * cell_orderNum = [AdressSelectTableViewCell cellWithTableView:tableView];
            cell_orderNum.leftTitString = @"订单号";
            cell_orderNum.inputTextField.textAlignment = NSTextAlignmentLeft;
//            cell_orderNum.inputTextField.text = @"HK201808141453257896";
            cell_orderNum.inputTextField.textColor = [UIColor colorWithHexString:@"#999999"];
            if (self.model) {
                ToPayOrderDataModel *dataModel = self.model.data.info;
                cell_orderNum.inputTextField.text = dataModel.orderId;
            }
            cell = cell_orderNum;
        }
            break;
        case 3:{
            FillGoodsMoneyTableViewCell * cell_money = [FillGoodsMoneyTableViewCell cellWithTableView:tableView];
            if (self.model) {
                ToPayOrderDataModel *orderData = self.model.data.info;
                cell_money.dataModel = orderData;
            }
            cell = cell_money;
        }
            break;
            
        default:
            break;
    }
    [cell setSepartionLineWith:lineModel_Half];
    return cell;
}

//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//    UIView * headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, kHeightProportion_In_iPhoneTriploid(10))];
//    return headerView;
//}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return kHeightProportion_In_iPhoneTriploid(10);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 1) {
        if (distribution == 2) return;
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(fillnSelectIndex:)]) {
        [self.delegate fillnSelectIndex:indexPath];
    }
}

- (void)setLastPageModel:(FillExpressModel *)lastPageModel
{
    _lastPageModel = lastPageModel;
    if ([lastPageModel.topStr isEqualToString:@"卖家承运"]) {
        distribution = 1;
        [self makeAddresData];
    } else {
        distribution = 2;
        [self requestGoodsType];
    }
    NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:0];
    [selfTableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (void)makeAddresData
{
    self.addressModel = nil;
}

- (void)setOrderID:(NSString *)orderID
{
    _orderID = orderID;
    [self requestDitributionType];
}

// 选择地址
- (void)setAddressModel:(MyAdressModel_Infos *)addressModel
{
    _addressModel = addressModel;
    [self refreshOneRow];
}

- (void)refreshOneRow
{
    NSIndexPath *index = [NSIndexPath indexPathForRow:1 inSection:0];
    [selfTableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationAutomatic];
}

// 联系卖家
- (void)call
{
    ToPayOrderDataOrderGoodsModel *goodsStr = self.model.data.info.orderGoods[0];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",goodsStr.contactPhone]]];
}

// 去付款
- (void)payMoney:(GLGWButton *)sender
{
    if (!self.model) {
        DLog(@"没有数据");
        return;
    }
}

#pragma mark - 收货方式接口
- (void)requestGoodsType
{
        NSInteger acountType = 0;
        if (self.accountType == AccountType_Ordinary) {
            acountType = 1;
        } else if (self.accountType == AccountType_FreeManagers) {
            acountType = 2;
        }
    NSDictionary *param = @{
                            @"orderId" : koString(self.orderID),  // 订单id
                            @"receivingGoodsType" : @(distribution), // 收获方式：1：卖家承运；2：到仓自提
                            @"type" : @(acountType)
                            };
    [GLGWRequestTool POST:[NSString stringWithFormat:@"%@%@",kApiPrefix,kMyOrderGoodAddress] lodingView:nil lodingTextString:@"" isLoding:YES parameters:param success:^(id  _Nullable response) {
        OrderGoodsAddressModel *addressModel = [OrderGoodsAddressModel yy_modelWithJSON:response];
        self.addressModel = addressModel.data.receiverInfo;
        [self refreshOneRow];
    } failure:^(NSError * _Nullable error) {
    }];
}

// 去支付订单列表信息
- (void)requestDitributionType
 {
    NSDictionary *param = @{
                            @"orderId" : koString(self.orderID)  // 订单id
                            };
    [GLGWRequestTool POST:[NSString stringWithFormat:@"%@%@",kApiPrefix,kMyOrderToPayList] lodingView:nil lodingTextString:@"" isLoding:YES parameters:param success:^(id  _Nullable response) {
        self.model = [ToPayOrderModel yy_modelWithJSON:response];
        [self makeTotalPrice];
        [self->selfTableView reloadData];
    } failure:^(NSError * _Nullable error) {
    }];
}

// 计算总价
- (void)makeTotalPrice
{
    NSArray *arr = self.model.data.info.orderGoods;
    NSInteger coutNum = 0;
    NSDecimalNumber *totalPrice = 0;
    for (ToPayOrderDataOrderGoodsModel *orderGoodsModel in arr) {
        coutNum += orderGoodsModel.goodsNum;
        NSDecimalNumber *pri = 0;
        if (orderGoodsModel.modifyPrice > 0) {
            pri = orderGoodsModel.modifyPrice;
        } else {
            pri = orderGoodsModel.price;
        }
        totalPrice = pri;
    }
    NSString *coutstr = [NSString stringWithFormat:@"%ld",coutNum];
    NSDecimalNumber *coutDeci = [NSDecimalNumber decimalNumberWithString:coutstr];
    NSDecimalNumber *totalPric = [coutDeci decimalNumberByMultiplyingBy:totalPrice];
    
    NSString *toStr = [NSString stringWithFormat:@"去付款%@元",totalPric];
    [fillView.payMoneyBut setTitle:toStr forState:UIControlStateNormal];
}
@end
